<template>
	<div
		class="page"
		style="padding: 20px 20px 0px 20px; width: 1200px; margin: 0 auto"
	>
		<div class="form-wrap">
			<el-form
				ref="formRef"
				:rules="formRules"
				:model="formValue"
				label-width="140px"
				style="width: 1200px; box-sizing: border-box"
			>
				<el-form-item label="Api Token" prop="token">
					<el-input v-model="formValue.token"></el-input>
				</el-form-item>
				<el-form-item label="测试接口" prop="interfaceCode">
					<el-select v-model="formValue.interfaceCode" clearable placeholder="">
						<el-option
							v-for="item in apiList"
							:key="item.id"
							:label="item.interfaceName"
							:value="item.interfaceCode"
						>
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="测试数据">
					<codeEditor
						:value="formValue.body"
						@setCodeValue="setBodyValue"
						height="300px"
					/>
				</el-form-item>
				<el-form-item label="响应报文">
					<codeEditor :value="responseValue" height="300px" />
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="submit">提交请求</el-button>
				</el-form-item>
			</el-form>
		</div>
	</div>
</template>
<script setup>
import request, { service2 } from "@/utils/request";
import { onMounted, reactive, ref } from "vue";
import codeEditor from "@/component/codeEditor.vue";
import { isJSON } from "@/utils/index.js";
let apiList = ref([]);
let formRef = ref();
let formRules = {
	token: [{ required: true, message: "请输入Api Token", trigger: "blur" }],
	interfaceCode: [{ required: true, message: "请选择接口", trigger: "blur" }],
};
let formValue = reactive({
	token: null,
	interfaceCode: null,
	body: "",
});
let responseValue = ref();
const getAppList = async () => {
	let res = await request({
		url: "/user/appInfo/list",
		method: "post",
		data: {
			pageNum: 1,
			pageSize: 99999,
		},
	});
};
const getApiList = async () => {
	let res = await request({
		url: "/user/interface/select",
		method: "post",
		data: {},
	});
	apiList.value = res.data;
};
onMounted(() => {
	getApiList();
});
const submit = async () => {
	formRef.value.validate(async (valid) => {
		console.log("valid", valid);
		if (valid) {
			let bodyParams = {};
			if (isJSON(formValue.body)) {
				bodyParams = JSON.parse(formValue.body);
			} else {
				bodyParams = {};
			}
			let token = localStorage.getItem("token");
			let res = await service2({
				url: "/user/interface/proxy",
				method: "post",
				headers: {
					Authorization: token || "",
				},
				data: {
					token: formValue.token,
					interfaceCode: formValue.interfaceCode,
					body: JSON.stringify(bodyParams),
				},
			});

			responseValue.value = JSON.stringify(res.data, null, 4);
		}
	});
};

const setBodyValue = (val) => {
	console.log("setBodyValue", val);
	formValue.body = val;
};
</script>

<style lang="scss" scoped>
.page {
	display: flex;
	justify-content: center;
	padding: 20px 0;
}
</style>
